'use strict';

const fs = require('fs');
const axios = require('axios');
const crypto = require('crypto');
const { query } = require('./utils/model.js');
const WxPay = require('wechatpay-node-v3');
const { appid, mch_id, appSecret, pay_api_key } = require('./config.js');

const md5 = require('md5');
let { genToken, checkToken } = require('./utils/token.js');
const { getOrder } = require('./utils/tools.js');

let succStatus = 0; // 表示成功
let failStatus = 1; // 表示失败

// 代表返回的数据结构
let response = {
  status: succStatus,
  message: '',
};

let qiniudomain = 'http://image.jxsaichuang.com/'; // 七牛云存储对象域名

// 定义控制器
let controller = {};

// 微信登录
controller.mplogin = async (req, res) => {
  let { code, username = '', avatar = '' } = req.body;
  console.log('code', code);
  let wxAPI = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code `;
  let { data } = await axios({
    url: wxAPI,
  });
  const openid = data.openid;
  let sql = `select * from users where openid='${openid}'`;
  let rows = await query(sql);
  if (rows.length == 0) {
    let sql2 = `insert into users(username,avatar,openid) values('${username}','${avatar}','${openid}')`;
    await query(sql2);
  }
  let sql3 = `select * from users where openid='${openid}'`;
  let rows3 = await query(sql3);
  let userInfo = rows3[0];
  res.json({
    token: genToken(userInfo, '3h'), // 1小时
    refreshToken: genToken(userInfo, '15d'), // 15天
    status: succStatus,
    message: '登录成功',
    userInfo,
  });
};

// 上传头像的方法
controller.upload = (req, res) => {
  let user_id = req.userInfo.id;
  if (req.file) {
    // 进行文件的重命名即可 fs.rename
    let { originalname, destination, filename } = req.file;
    let dotIndex = originalname.lastIndexOf('.');
    let ext = originalname.substring(dotIndex);
    let oldPath = `${destination}${filename}`;
    let newPath = `${destination}${filename}${ext}`;
    fs.rename(oldPath, newPath, async (err) => {
      if (err) {
        throw err;
      }
      // 更新 update
      let sql = `update users set avatar = '${newPath}' where id = '${user_id}' `;
      let result = await query(sql);
      let response = {};
      if (result.affectedRows > 0) {
        res.json({
          message: '上传成功',
          status: 0,
          src: newPath,
        });
      } else {
        res.json({
          message: '上传失败',
          code: 1,
          src: '',
        });
      }
    });
  } else {
    res.json({
      message: '请上传文件',
      code: 2,
      src: '',
    });
  }
};

// 获取轮播图数据
controller.getlunbo = (req, res) => {
  let response = {
    status: succStatus,
    message: [
      {
        url: 'http://www.baidu.com',
        img: `https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000366/100038004389/FocusFullshop/CkRqZnMvdDEvMTI4NDUwLzI4LzM0ODY1LzI4NjgwMy82NGYzOGU2MkYwYjA4NTdkNy81N2U3MjU5MGJkNGM1YmM1LnBuZxIJMy10eV8wXzU0MAI47ot6QhYKEkFwcGxlaVBob25lIDE0IFBybxABQhAKDOWlvei0p-axh-iBmhACQhAKDOeri-WNs-aKoui0rRAGQgoKBuS8mOmAiRAHWKWd69X0Ag/cr/s/q.jpg`,
      },
      {
        url: 'http://jd.com',
        img: `https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000367/100020990995/FocusFullshop/CkJqZnMvdDEvMTg0MDUxLzQvMzc0NzMvMzAzMTgvNjRlZjliYTJGZGIyODhhY2IvYjhjZDA3MTE5MTViYjRiZi5wbmcSCTUtdHlfMF81NjACOO-LekIQCgznvo7nmoTnqbrosIMQAUIQCgznpo_liKnni4LkuqsQAkIQCgznq4vljbPmiqLotK0QBkIKCgbotoXlgLwQB1iT6NzN9AI/cr/s/q.jpg`,
      },
      {
        url: 'https://www.tmall.com/',
        img: `https://imgcps.jd.com/ling-cubic/ling4/lab/amZzL3QxLzE3NDQ0MS8zOC8yMjk0LzI2MzgyMi82MDZjMWUxY0U1ODFlNjFlOS9hYzFmNzRmNGVlZGE4MDZhLnBuZw/5Lqs6YCJ5aW96LSn/5L2g5YC85b6X5oul5pyJ/1635183804528672769/cr/s/q.jpg`,
      },
    ],
  };
  res.json(response);
};

// 新闻列表
controller.getnewslist = async (req, res) => {
  let page = parseInt(req.query.page) || 1;
  let pagesize = parseInt(req.query.pagesize) || 10;
  let offset = (page - 1) * pagesize;
  let response = {
    status: succStatus,
    message: '',
  };
  let sql =
    " SELECT id,title,add_time,click,concat('" +
    qiniudomain +
    "',img_url) as img_url FROM news where img_url > '' and status = 1 limit " +
    offset +
    ',' +
    pagesize +
    ' ';
  let rows = await query(sql);
  response.message = rows;
  res.json(response);
};

// 新闻详情
controller.getnew = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };

  let news_id = req.params.news_id || 0;

  let sql =
    'select id,title,click,add_time,content from news where id=' + news_id;
  let rows = await query(sql);
  response.status = rows[0] ? 1 : 0;
  response.message = rows[0] || {};
  res.json(response);
};

// 推荐商品
controller.recommend = async (req, res) => {
  let { page = 1, limit = 6 } = req.query;
  let response = {
    status: succStatus,
    message: '',
  };
  let offset = (page - 1) * limit;
  let sql = `select t1.* , concat('${qiniudomain}',t1.img_url) as img_url,t2.market_price, t2.sell_price 
                from goods t1 left join goods_specification t2 
                on t1.id = t2.goods_id where t1.status = 1  limit ${offset}, ${limit}`;
  let rows = await query(sql);
  response.message = rows;
  res.json(response);
};

// 商品列表
controller.getListgoods = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };
  let page = req.query.page || 1;
  let pagesize = req.query.pagesize || 10;

  let offset = (page - 1) * pagesize;

  let sql = `SELECT a.id,a.title,a.add_time,left(a.zhaiyao,25) as zhaiyao,
          a.click,concat('${qiniudomain}',a.img_url) as img_url,
          b.sell_price,b.market_price,b.stock_quantity 
          FROM goods as a,goods_specification b 
          where a.id = b.goods_id and a.status = 1
          limit ${offset},${pagesize} `;
  let rows = await query(sql);
  //获取数据成功
  response.message = rows;
  res.json(response);
};

// 获取商品标题，价格，规格信息
controller.getgoodsinfo = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };
  let goods_id = req.params.id || 0;
  let sql = ` SELECT t1.id,t1.title,t1.add_time,t1.zhaiyao,t1.content,
                t2.goods_no,t2.stock_quantity,t2.market_price,t2.sell_price 
                FROM goods t1 left join  goods_specification t2 
                on t1.id = t2.goods_id where t1.id = ${goods_id} `;
  let rows = await query(sql);
  response.status = rows[0] ? 1 : 0;
  response.message = rows[0] || {};
  res.json(response);
};

// 商品搜索
controller.search = async (req, res) => {
  let {
    value = '',
    sort = 'buy',
    order = 'desc',
    page = 1,
    pagesize = 10,
  } = req.query;

  let offset = parseInt((page - 1) * pagesize);
  // 设置别名
  if (['sell_price', 'market_price'].includes(sort)) {
    sort = 'b.' + sort;
  }

  let sql = `SELECT a.likes,a.buy,a.id,a.title,a.add_time,left(a.zhaiyao,25) as zhaiyao,
      a.click,concat('${qiniudomain}',a.img_url) as img_url,
      b.sell_price,b.market_price,b.stock_quantity FROM goods as a,goods_specification b 
      where a.id = b.goods_id and a.status = 1 and title like '%${value}%'  
      order by ${sort} ${order} 
      limit ${offset},${pagesize}`;

  try {
    let rows = await query(sql);
    res.json(rows);
  } catch (e) {
    res.json({ message: '查询数据失败' });
  }
};

// 获取购物车列表数据
controller.getshopcarlist = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };
  let ids = req.params.ids;

  let sql = `SELECT  t1.id,t1.title,t2.sell_price FROM goods t1 
          LEFT JOIN goods_specification t2 ON (t1.id = t2.goods_id)
          where t1.id IN(${ids})`;

  let rows;
  try {
    rows = await query(sql);
  } catch (err) {
    res.json({ message: [] });
    return;
  }

  // 获取商品的缩略图
  let sql2 = `SELECT  goods_id,thumb_path from goods_albums where goods_id in (${ids}) and selected = 1`;
  let thumbs = await query(sql2);
  // 获取购物车商品相应的图片
  rows = rows.map((item) => {
    let index = thumbs.findIndex((item2) => item.id == item2.goods_id);
    if (index > -1) {
      item.thumb_path = qiniudomain + thumbs[index].thumb_path;
    }
    return item;
  });

  response.message = rows;
  res.json(response);
};

// 获取商品缩略图
controller.getthumbimages = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };

  let { id = 0 } = req.params;

  let sql =
    'select concat("' +
    qiniudomain +
    '",thumb_path)  as src from goods_albums where goods_id =' +
    id;
  let rows = await query(sql);
  response.message = rows;
  res.json(response);
};

// 获取评论信息
controller.getcomments = async (req, res) => {
  let response = {
    status: succStatus,
    message: '',
  };

  let news_id = req.params.news_id || 0;
  let pageindex = req.query.pageindex || 1;
  let pagesize = req.query.pagesize || 10;

  let offset = (pageindex - 1) * pagesize;

  let sql = `select id,user_name,add_time,content from comment   
                where news_id = ${news_id} order by add_time asc 
                limit ${offset},${pagesize}`;
  let rows = await query(sql);
  response.message = rows;
  res.json(response);
};

// 提交评论数据
controller.postcomment = async (req, res) => {
  let news_id = req.params.news_id;
  let content = req.body.content;

  let response = {
    status: succStatus,
    message: '',
  };

  let sql = `insert into  comment(news_id,user_name,content,add_time)
              values (${news_id},'匿名用户','${content}',NOW())`;
  try {
    let rows = await query(sql);
    response.message = '评论提交成功';
    response.insertId = rows.insertId;
  } catch (e) {
    response.message = e.message;
    response.status = failStatus;
  }

  res.json(response);
};

// 用户登录接口
controller.login = async (req, res) => {
  let { username, password } = req.body;
  password = md5(password);

  let sql = `select id,username,avatar,tel,email,openid,sex from users where username='${username}' and password='${password}'`;
  let rows = await query(sql);
  if (!rows.length) {
    res.json({
      status: failStatus,
      message: '用户名或密码错误',
    });
  } else {
    let userInfo = rows[0];
    res.json({
      token: genToken(userInfo, '3h'), // 1小时
      refreshToken: genToken(userInfo, '15d'), // 15天
      status: succStatus,
      message: '登录成功',
      userInfo,
    });
  }
};

// 用户注册接口
controller.register = async (req, res) => {
  let { username, password } = req.body;
  //1. 校验用户名唯一性
  let sql = `select id  from users where username='${username}'`;
  let rows = await query(sql);
  if (rows.length) {
    res.json({
      status: failStatus,
      message: '用户名已被占用',
    });
  } else {
    password = md5(password);
    let sql = `insert into users(username,password) values('${username}','${password}')`;
    let rows = await query(sql);

    let status = rows.affectedRows ? 0 : 1;
    let message = rows.affectedRows ? '注册成功' : '注册失败';
    let response = {
      status,
      message,
    };
    res.json(response);
  }
};

// 获取用户所有收货地址
controller.getaddress = async (req, res) => {
  let user_id = req.userInfo.id;
  let sql = `select * from address where user_id = ${user_id}`;
  let datas = await query(sql);
  datas = datas.map((item) => {
    item.address = item.addressDetail;
    item.isDefault = item.isDefault == 1 ? true : false;
    return item;
  });
  res.json(datas);
};

// 用户添加收货地址
controller.addaddress = async (req, res) => {
  let user_id = req.userInfo.id;
  let {
    name,
    tel,
    province,
    city,
    country,
    postalCode,
    isDefault,
    areaCode,
    addressDetail,
  } = req.body;
  isDefault = isDefault == true ? 1 : 0;
  let sql = `insert into 
                address(name,tel,province,city,country,postalCode,isDefault,areaCode,addressDetail,user_id,add_time) 
                values('${name}', '${tel}', '${province}', '${city}', '${country}', '${postalCode}', 
                ${isDefault}, '${areaCode}', '${addressDetail}',${user_id},now() )`;
  try {
    let rows = await query(sql);
    response.status = rows.affectedRows ? 0 : 1;
    response.message = rows.affectedRows ? '添加地址成功' : '添加地址失败';
    let insertId = rows.insertId;
    // 修改默认收货地址
    let sql2 = `update address set isDefault = 0 where user_id=${user_id} and id != ${insertId}`;
    if (isDefault == 1) {
      query(sql2);
    }
  } catch (e) {
    response.status = failStatus;
    response.message = e.message;
  }

  res.json(response);
};

// 用户删除收货地址
controller.deladdress = async (req, res) => {
  let { address_id } = req.query;
  let sql = `delete from address where id=${address_id}`;

  try {
    let rows = await query(sql);
    response.status = rows.affectedRows ? 0 : 1;
    response.message = rows.affectedRows ? '添加删除成功' : '删除地址失败';
  } catch (e) {
    response.status = failStatus;
    response.message = e.message;
  }
  res.json(response);
};

// 用户编辑收货地址
controller.updateaddress = async (req, res) => {
  let { address_id } = req.query;
  let user_id = req.userInfo.id;
  let {
    name,
    tel,
    province,
    city,
    country,
    postalCode,
    isDefault,
    areaCode,
    addressDetail,
  } = req.body;

  isDefault = isDefault == true ? 1 : 0;
  let arr = [
    address_id,
    name,
    tel,
    province,
    city,
    country,
    postalCode,
    addressDetail,
    areaCode,
  ];

  let isCorrect = true; // 记录参数是否错误
  arr.forEach((v) => {
    if (!v) {
      isCorrect = false;
    }
  });

  if (!isCorrect) {
    res.json({
      status: 1,
      message: '接口参数非法，请检查',
    });
  } else {
    let sql = `update address set name='${name}', tel='${tel}', province='${province}', 
                city='${city}', country='${country}', 
                postalCode='${postalCode}', isDefault=${isDefault}, 
                areaCode='${areaCode}', addressDetail = '${addressDetail}',
                user_id='${user_id}', add_time=now()
                where id = ${address_id}
                `;
    // 修改默认收货地址
    let sql2 = `update address set isDefault = 0 where user_id=${user_id} and id != ${address_id}`;
    if (isDefault == 1) {
      await query(sql2);
    }

    try {
      let rows = await query(sql);
      response.status = rows.affectedRows ? 0 : 1;
      response.message = rows.affectedRows ? '修改地址成功' : '修改地址失败';
    } catch (e) {
      response.status = failStatus;
      response.message = e.message;
    }

    res.json(response);
  }
};

// 用户提交订单
controller.commitorder = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let user_id = req.userInfo.id;
  // 入库，操作，校验用户，订单金额
  let { order_id, address_id, total_price, number, goods_ids } = req.body;
  let isCorrect = true;
  // 检验参数，必填
  [user_id, order_id, address_id, total_price, number, goods_ids].forEach(
    (v) => {
      if (!v) {
        isCorrect = false;
      }
    }
  );

  if (!isCorrect) {
    res.json({
      code: 200001,
      message: '接口参数错误，请检查',
    });
  } else {
    // 获取订单地址信息
    let sql = 'select * from address where id = ' + address_id;
    let addressInfo = await query(sql);
    let address_info = JSON.stringify({
      ...addressInfo[0],
    });
    // 准备支付订单信息,订单入库信息：
    let orderData = {
      ...req.body,
      user_id,
      actual_price: 0.01,
      pay_way: '微信支付',
      status: 0, // 默认0为未付款
      is_take: 0, // 未收货
      is_out: 0, // 未发货
      address_info,
      add_time: Math.floor(new Date().getTime() / 1000),
    };
    try {
      let result = await query('INSERT INTO goods_order SET ?', orderData);
      res.json({ message: '生成订单成功', code: 20000 });
    } catch (err) {
      res.json({ message: '生成订单失败', code: 20002 });
    }
  }
};

// 返回支付二维码
controller.payqrcode = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let { order_id } = req.query;
  const pay = new WxPay({
    appid: appid,
    mchid: mch_id,
    publicKey: fs.readFileSync('./data/apiclient_cert.pem'), // 公钥
    privateKey: fs.readFileSync('./data/apiclient_key.pem'), // 秘钥
  });

  const params = {
    description: '商品支付',
    out_trade_no: order_id,
    notify_url: 'http://letaoapi.jxsaichuang.com/qrcodenotify',
    amount: {
      total: 1,
    },
    scene_info: {
      payer_client_ip: '127.0.0.1',
    },
  };
  const result = await pay.transactions_native(params);
  res.json(result);
};

// 查询微信支付订单状态，修改数据库订单状态
controller.queryPayOrder = async (req, res) => {
  let { order_id } = req.query;
  const pay = new WxPay({
    appid: appid,
    mchid: mch_id,
    publicKey: fs.readFileSync('./data/apiclient_cert.pem'), // 公钥
    privateKey: fs.readFileSync('./data/apiclient_key.pem'), // 秘钥
  });
  const result = await pay.query({ out_trade_no: order_id });
  let { status, data, error } = result;
  if (status === 200 && data.trade_state === 'SUCCESS') {
    console.log('++++++++++查询订单支付成功++++++++++++');
    // 订单支付成功
    // 订单信息：订单号、交易号、微信用户openid、支付时间
    let {
      out_trade_no,
      transaction_id,
      payer: { openid },
      success_time,
    } = data;
    // 更新数据订单信息：改为： 已付款
    let sql = `update goods_order set status = 1,openid = '${openid}',
              transaction_id = '${transaction_id}',
              success_time = '${success_time}' 
              where order_id = '${out_trade_no}'`;
    await query(sql);
    res.json({ code: 20000, message: data.trade_state_desc });
  } else {
    res.json({ code: 20001, message: '订单不存在或订单未支付' });
  }
};

// 获取用户订单
controller.userorder = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let user_id = req.userInfo.id;
  let { page = 1, pagesize = 8 } = req.query;
  let offset = (page - 1) * pagesize;
  let sql = `select * from goods_order where user_id = ${user_id} order by id desc limit ${offset}, ${pagesize}`;
  // 获取用户订单
  let orders = await query(sql);
  // 获取订单中的商品
  let goods_ids_arr = orders.map(({ goods_ids }) => goods_ids);
  console.log(user_id);

  // 批量promise并发执行
  let promiseArr = [];
  goods_ids_arr.forEach((ids) => {
    let sql = `select  t1.id,t1.title,t2.sell_price, t3.thumb_path
    FROM goods t1 
    LEFT JOIN goods_specification t2 ON (t1.id = t2.goods_id)
    LEFT JOIN goods_albums t3 ON (t1.id = t3.goods_id)
    where t1.id IN(${ids})  and  t3.selected = 1`;
    promiseArr.push(query(sql));
  });

  let order_goods = await Promise.all(promiseArr);
  // 整合订单商品图片
  order_goods = order_goods.map((item) => {
    item.forEach((item2) => {
      item2.thumb_path = qiniudomain + item2.thumb_path;
    });
    return item;
  });

  // 将订单商品聚合到订单goods属性中
  orders = orders.map((order, index) => {
    order.goods = order_goods[index];
    order.address_info = JSON.parse(order.address_info || '{}');
    return order;
  });

  res.json(orders);
};

// 查询单条订单信息
controller.getorder = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let { order_id } = req.query;

  let response = {};
  if (!order_id) {
    res.json({ status: 0, message: '订单号参数有误' });
  } else {
    let sql = `select * from goods_order where order_id = '${order_id}'`;
    let rows = await query(sql);
    response = rows[0] || {};
    if (rows[0]) {
      response.address_info = JSON.parse(response.address_info || '{}');
    }
    res.json(response);
  }
};

// 刷新token
controller.refreshToken = (req, res) => {
  const { refreshToken } = req.body;
  // 校验token
  let userInfo = checkToken(refreshToken);

  if (userInfo === false) {
    res.status(401).json({
      message: '刷新token失败',
    });
  } else {
    // 生成新token
    delete userInfo.iat;
    delete userInfo.exp;
    let token = genToken(userInfo, '3h'); // 10s
    res.json({ token, userInfo });
  }
};

// 小程序支付异步通知
controller.mpnotify = (req, res) => {
  console.log('--------小程序异步通知~~~~~~~~~~~~', req.body);
  res.json({ message: '小程序异步通知' });
};

// 扫码支付异步通知
controller.qrcodenotify = async (req, res) => {
  console.log('---ddd+++---扫码支付异步通知~~~~~~~~~~~~');
  res.json({ message: '扫码支付异步通知' });
};

controller.kuaidi = (req, res) => {
  let data = [
    {
      time: '2021.12.07 16:11 星期二',
      location: '【佛山市】已离开 广东佛山分拨交付中心；发往 广东广州南沙公司',
    },
    {
      time: '2021.12.07 16:07',
      location: '【佛山市】已到达 广东佛山分拨交付中心',
    },
    {
      time: '2021.12.07 02:05',
      location:
        '【南宁市】已离开 广西南宁分拨交付中心；发往 广东佛山分拨交付中心',
    },
    {
      time: '2021.12.06 11:18',
      location: '【南宁市】已到达 广西南宁分拨交付中心',
    },
    {
      time: '2021.12.05 13:42 星期天',
      location:
        '【南宁市】广西南宁分拨营销市场部南韵分部-陈惠玲（15114917493） 已揽收',
    },
  ];
  res.json(data);
};

// 获取商品分类
controller.getcategory = async (req, res) => {
  let sql = 'select * from category order by id desc';
  let rows = await query(sql);
  res.json(rows);
};

// 取消订单
controller.cancelorder = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let { order_id = 0 } = req.query;
  let sql = `update goods_order set is_cancel = 1 where order_id = '${order_id}'`;
  await query(sql);
  let response = {
    code: 20000,
    message: '取消订单成功',
  };
  res.json(response);
};

// 删除订单
controller.delorder = async (req, res) => {
  if (!req?.userInfo?.id) {
    res.json({
      code: 20004,
      message: '请求错误',
    });
    return;
  }
  let { order_id = 0 } = req.query;
  let sql = `delete from goods_order  where order_id = '${order_id}'`;
  await query(sql);
  let response = {
    code: 20000,
    message: '删除订单成功',
  };
  res.json(response);
};

// 获取分类下面商品
controller.getcategorygoods = async (req, res) => {
  let { category_id = 0 } = req.query;
  let sql = `select t1.id,t1.title,concat('${qiniudomain}',t2.thumb_path) as thumb_path, 
        t3.market_price, t3.sell_price 
        from goods t1   
        left join goods_albums t2 on t1.id = t2.goods_id
        left join goods_specification t3 on t1.id = t3.goods_id
        where t1.category_id = ${category_id} and t2.selected = 1`;
  let rows = await query(sql);
  res.json(rows);
};

// 获取历史浏览
controller.history = async (req, res) => {
  let { page, pagesize } = req.query;
  let offset = (page - 1) * pagesize;
  let sql = `select t2.id, t2.title, concat('${qiniudomain}',t2.img_url) as img_url, t2.buy, t3.market_price from history t1 
            left join goods t2 on t1.goods_id = t2.id
            left join goods_specification t3 on t1.goods_id = t3.goods_id
            where t1.user_id=${req?.userInfo?.id} order by t1.id desc
            limit ${offset},${pagesize}`;
  let result = await query(sql);
  res.json(result);
};
// 添加历史浏览
controller.addhistory = async (req, res) => {
  let { goods_id } = req.query;
  let sql1 = `delete from history where user_id=${req.userInfo.id} and goods_id=${goods_id}`;
  await query(sql1);
  let sql2 = `insert into history(user_id,goods_id) values(${req.userInfo.id},${goods_id})`;
  let { affectedRows } = await query(sql2);
  if (affectedRows > 0) {
    res.json({ code: 20000, message: 'success' });
  } else {
    res.json({ code: 20001, message: 'fali' });
  }
};

//修改密码
controller.updatePassword = async (req, res) => {
  console.log(req.userInfo.id);
  let { newPassword } = req.query;
  newPassword = md5(newPassword);
  let sql = `update users set password ='${newPassword}' where id = ${req.userInfo.id}`;
  let { affectedRows } = await query(sql);
  if (affectedRows > 0) {
    res.json({ code: 20000, message: '修改成功' });
  } else {
    res.json({ code: 20001, message: '修改失败' });
  }
};

// 导出模块
module.exports = controller;
